package com.bing.my.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bing.common.config.Result;
import com.bing.my.entity.User;
import com.bing.my.entity.vo.VoUserInfo;
import com.bing.my.mapper.UserMapper;
import com.bing.my.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bing.utils.JwtUtil;
import com.bing.utils.UtilConstants;
import io.jsonwebtoken.Claims;
import org.springframework.util.Assert;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bing
 * @since 2021-09-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public Result<?> insert(User user) {
        if (userMapper.insert(user) == 1) {
            return Result.success();
        }
        return Result.error();
    }

    @Override
    public Result<?> deleteById(Integer id) {
        if (userMapper.deleteById(id) == 1) {
            return Result.success();
        }
        return Result.error();
    }

    @Override
    public Result<?> update(User user) {
        if (userMapper.updateById(user) == 1) {
            return Result.success();
        }
        return Result.error();
    }

    @Override
    public Result<?> selectOne(User user) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        wrapper.eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword());
        User selectOne = userMapper.selectOne(wrapper);
        Assert.notNull(selectOne, "用户不存在");
        if (selectOne != null) {
            // 生成token
            String jwt = JwtUtil.createJWT(UtilConstants.JWT_JWT_SEC, UtilConstants.JWT_TTL_MILLIS,
                    selectOne.getUsername());
            return Result.success(JSONUtil.parse("{'token':'" + jwt + "'}"));
        }
        return Result.error(50000,"用户名或密码错误!");
    }

    @Override
    public Result<?> checkToken(Claims claims) {
        //判读token是否过期
        if (claims.getExpiration().getTime() >= System.currentTimeMillis()) {
            String username = (String) claims.get("username");
            User user = this.findUserByUsername(username);
            // 判断token用户名是否跟数据库匹配
            if (user.getUsername().equals(username)) {
                VoUserInfo info = new VoUserInfo();
                info.setName(username);
                info.setAvatar(user.getAvatar());
                info.setRoles(Arrays.asList(user.getRoles()));
                return Result.success(info);
            }
        }
        return Result.error(50014, "令牌过期");
    }


    @Override
    public Result<?> logout(String token) {
        Claims claims = JwtUtil.parseJWT(UtilConstants.JWT_JWT_SEC, token);
        String username = (String) claims.get("username");
        if (this.findUserByUsername(username) != null) {
            return Result.success();
        }
        return Result.error();
    }

    @Override
    public User findUserByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectOne(wrapper);
    }
}
